﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Web.Routing;
using System.Web;
using System.IO;    
using Tools;

namespace ViewDataBusiness
{
    public static class Factory
    {
        public static string GetPath(RouteValueDictionary KeyList, string BaseForder, string SubForder, string Type)
        {
            string  Key = GetKey(KeyList, BaseForder);
            if (Key != null)
            {
                string Path = ConfigurationManager.AppSettings[Type];
                if (Path[0] == '/')
                    Path = HttpContext.Current.Server.MapPath(Path + "/" + Key + (SubForder == "" ? "" : "/" + GetKey(KeyList, SubForder)));
                else
                    Path += "\\" + Key + (SubForder == "" ? "" : "\\" + GetKey(KeyList, SubForder));
                return Path;
            }
            else
            {
                return null;
            }
        }

        private static string GetKey(RouteValueDictionary KeyList, string Value)
        {
            switch (Value)
            {
                case "#KeyA":
                    return KeyList["KeyA"] != null ? KeyList["KeyA"].ToString() : null;
                case "#KeyB":
                    return KeyList["KeyB"] != null ? KeyList["KeyB"].ToString() : null;
                case "#KeyC":
                    return KeyList["KeyC"] != null ? KeyList["KeyC"].ToString() : null;
                case "#KeyD":
                    return KeyList["KeyD"] != null ? KeyList["KeyD"].ToString() : null;
            }
            return Value;
        }

        private static Dictionary<string, List<string>> GetOperationColums(ViewSetting viewSetting, List<string> userPermissions, Dictionary<string, List<Dictionary<string, object>>> ActionJsonParameter, Dictionary<string, List<Dictionary<string, object>>> JsonParameter)
        {
            Dictionary<string, List<string>> OperationColums = new Dictionary<string, List<string>>();
            Dictionary<string, List<Dictionary<string, object>>> Temp = null;
            if (ActionJsonParameter != null)
                if (ActionJsonParameter.ContainsKey("操作列"))
                    Temp = ActionJsonParameter;

            if (JsonParameter != null)
                if (JsonParameter.ContainsKey("操作列"))
                    Temp = JsonParameter;

            if (Temp != null)
                foreach (Dictionary<string, object> p in Temp["操作列"])
                    if (p.ContainsKey("权限名称") && p.ContainsKey("连接名称") && p.ContainsKey("连接格式"))
                        if (!PermissionCheck.HasPermission(userPermissions, p["权限名称"].ToString()))
                        {
                            OperationColums.Add(p["连接名称"].ToString(), null);
                        }
                        else
                        {
                            OperationColums.Add(p["连接名称"].ToString(), new List<string>() { p.ContainsKey("替换字段") ? p["替换字段"].ToString() : null, p["连接格式"].ToString().IndexOf("javascript:") == -1 ? PreUrl.AddHttp(PreUrl.AddPermissions(p["连接格式"].ToString(), viewSetting.Permissions)) : p["连接格式"].ToString() });
                            if (p.ContainsKey("{0}"))
                                OperationColums.Last().Value.Add(p["{0}"].ToString());
                            if (p.ContainsKey("{1}"))
                                OperationColums.Last().Value.Add(p["{1}"].ToString());
                            if (p.ContainsKey("{2}"))
                                OperationColums.Last().Value.Add(p["{2}"].ToString());
                            if (p.ContainsKey("{3}"))
                                OperationColums.Last().Value.Add(p["{3}"].ToString());
                        }
            return OperationColums;
        }

        private static int GetMaxRecord(Dictionary<string, List<Dictionary<string, object>>> ActionJsonParameter, Dictionary<string, List<Dictionary<string, object>>> JsonParameter)
        {
            int R = 0;
            if (ActionJsonParameter != null)
                if (ActionJsonParameter.ContainsKey("记录控制"))
                    R = int.Parse(ActionJsonParameter["记录控制"][0]["返回数量"].ToString());
            if (R == 0)
                if (JsonParameter != null)
                    if (JsonParameter.ContainsKey("记录控制"))
                        switch (JsonParameter["记录控制"][0]["返回数量"].ToString())
                        {
                            case "#Get":
                                if (HttpContext.Current.Request.QueryString.AllKeys.Contains("BackMaxRecord"))   
                                    R = int.Parse(HttpContext.Current.Request.QueryString["BackMaxRecord"]);
                                else                                                                               
                                    R = int.Parse(HttpContext.Current.Request.QueryString["MaxRecord"]);
                                break;
                            case "#CookieGet":
                                if (HttpContext.Current.Request.QueryString.AllKeys.Contains("BackMaxRecord"))
                                    R = int.Parse(HttpContext.Current.Request.QueryString["BackMaxRecord"]);
                                else
                                    if (HttpContext.Current.Request.Cookies.AllKeys.Contains("MaxRecord"))
                                        R = int.Parse(HttpContext.Current.Request.Cookies["MaxRecord"].Value);
                                    else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("MaxRecord"))
                                        R = int.Parse(HttpContext.Current.Request.QueryString["MaxRecord"]);
                                    else
                                        R = 15;
                                break;
                            default:
                                R = int.Parse(JsonParameter["记录控制"][0]["返回数量"].ToString());
                                break;
                        }
            if (R > 0)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie("MaxRecord", R.ToString()) { Expires = DateTime.MaxValue });
            return R;
        }

        private static int GetStartRecord(Dictionary<string, List<Dictionary<string, object>>> ActionJsonParameter, Dictionary<string, List<Dictionary<string, object>>> JsonParameter)
        {
            if (ActionJsonParameter != null)
                if (ActionJsonParameter.ContainsKey("记录控制"))
                    return (int)ActionJsonParameter["记录控制"][0]["开始记录"];
            if (JsonParameter != null)
                if (JsonParameter.ContainsKey("记录控制"))
                    if (JsonParameter["记录控制"][0]["开始记录"].ToString() == "#Get")
                        return int.Parse(HttpContext.Current.Request.QueryString["StartRecord"]);
                    else
                        return (int)JsonParameter["记录控制"][0]["开始记录"];
            return -1;
        }

        private static string GetDataFormat(Dictionary<string, List<Dictionary<string, object>>> ActionJsonParameter, Dictionary<string, List<Dictionary<string, object>>> JsonParameter)
        {
            if (ActionJsonParameter != null)
                if (ActionJsonParameter.ContainsKey("列表格式"))
                    return ActionJsonParameter["列表格式"][0]["格式名称"].ToString();
            if (JsonParameter != null)
                if (JsonParameter.ContainsKey("列表格式"))
                    return JsonParameter["列表格式"][0]["格式名称"].ToString();
            return "Default";
        }

        public static void ViewFactory(ViewSetting viewSetting, RouteValueDictionary KeyList, List<string> userPermissions)
        {
            if (viewSetting.Operations != null)
            {
                DataBusiness dataBusiness = null;

                foreach (string m in viewSetting.Operations.Keys)
                {
                    if (!viewSetting.Operations[m].Asynchronous && PermissionCheck.HasPermission(userPermissions, viewSetting.Operations[m].Permission))
                        switch (viewSetting.Operations[m].OperationType)
                        {
                            case OperationType.FillData:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                Dictionary<string, List<Dictionary<string, object>>> JsonParameter = null;
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m].JsonParameter))
                                    JsonParameter = new JavaScriptSerializer().Deserialize<Dictionary<string, List<Dictionary<string, object>>>>(viewSetting.Operations[m].JsonParameter);
                                viewSetting.Operations[m].OperationData = dataBusiness.FillData(viewSetting.Operations[m], null, GetDataFormat(null, JsonParameter), GetOperationColums(viewSetting, userPermissions, null, JsonParameter), GetStartRecord(null, JsonParameter), GetMaxRecord(null, JsonParameter));
                                break;
                            case OperationType.ExecuteNonQuery:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                viewSetting.Operations[m].OperationData = dataBusiness.ExecuteNonQuery(viewSetting.Operations[m], null);
                                break;
                            case OperationType.ExecuteScalar:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                viewSetting.Operations[m].OperationData = dataBusiness.ExecuteScalar(viewSetting.Operations[m], null);
                                string ReturnType = "";
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m].JsonParameter))
                                    ReturnType = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m].JsonParameter)["返回类型"];
                                switch (ReturnType)
                                {
                                    case "新增对象链接":
                                        string AutoID = dataBusiness.ExecuteScalar(viewSetting.Operations[m], null).ToString();
                                        viewSetting.Operations[m].OperationData = AsynchronousLogin.GetAsynchronousLoginUrl(HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("&AsynchronousLoginKey=")).Replace("ViewProcess/Action/", "ViewProcess/Show/").Replace("/-1", "/" + AutoID), HttpContext.Current.Request.QueryString["Permissions"]);
                                        break;
                                    default:
                                        viewSetting.Operations[m].OperationData = dataBusiness.ExecuteScalar(viewSetting.Operations[m], null);
                                        break;
                                }
                                break;
                            case OperationType.ExecuteScalarNull:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                if (dataBusiness.ExecuteScalar(viewSetting.Operations[m], null) != null)
                                {
                                    string Messing = "对象重复！";
                                    if (!String.IsNullOrEmpty(viewSetting.Operations[m].JsonParameter))
                                        Messing = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m].JsonParameter)["非空返回信息"];
                                    foreach (QueryParameter n in viewSetting.Operations[m].Query.Parameters)
                                        Messing = Messing.Replace(n.Name, n.Value);
                                    throw new Exception(Messing);
                                }
                                break;
                            case OperationType.FileList:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "InternalFiles");
                                    if (FilePath != null)
                                        if (Directory.Exists(FilePath))
                                        {
                                            string[] FileNames = Directory.GetFiles(FilePath);
                                            for (int i = 0; i < FileNames.Length; i++)
                                                FileNames[i] = Path.GetFileName(FileNames[i]);
                                            viewSetting.Operations[m].OperationData = FileNames;
                                        }
                                }
                                break;
                            case OperationType.ImageList:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "Images");
                                    if (FilePath != null)
                                        if (Directory.Exists(FilePath))
                                        {
                                            string[] FileNames = Directory.GetFiles(FilePath);
                                            for (int i = 0; i < FileNames.Length; i++)
                                                FileNames[i] = Path.GetFileName(FileNames[i]);
                                            viewSetting.Operations[m].OperationData = FileNames;
                                        }
                                }
                                break;
                        }
                    viewSetting.Operations[m].Query = null;
                }
            }
        }

        public static List<object> ActionFactory(ViewSetting viewSetting, RouteValueDictionary KeyList, List<string> userPermissions, List<List<ActionOperation>> ActionParameters)
        {
            try
            {
                List<object> ReturnData = new List<object>();
                DataBusiness dataBusiness = null;

                foreach (List<ActionOperation> m in ActionParameters)
                    foreach (ActionOperation n in m)
                        if (!viewSetting.Operations.ContainsKey(n.OperationKey))
                            throw new Exception("没有找到操作：" + n.OperationKey + "。");
                        else if (!PermissionCheck.HasPermission(userPermissions, viewSetting.Operations[n.OperationKey].Permission))
                            throw new Exception("没有权限：" + viewSetting.Operations[n.OperationKey].Permission + "，无法进行操作：" + n.OperationKey + "。");
                                                                                                    
                foreach (List<ActionOperation> m in ActionParameters)
                    if(m.Count > 1)
                    {
                        if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                        List<Operation> operations = new List<Operation>();
                        List<Dictionary<string, object>> actionParameters = new List<Dictionary<string, object>>();

                        foreach(ActionOperation n in m)
                            if (viewSetting.Operations[n.OperationKey].OperationType == OperationType.ExecuteNonQuery)
                            {
                                operations.Add(viewSetting.Operations[n.OperationKey]);
                                actionParameters.Add(n.Parameters);
                            }

                        ReturnData.Add(dataBusiness.ExecuteNonQuery(operations, actionParameters));
                    }
                    else if (m.Count == 1)
                        switch (viewSetting.Operations[m[0].OperationKey].OperationType)
                        {
                            case OperationType.FillData:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                Dictionary<string, List<Dictionary<string, object>>> JsonParameter = null;
                                Dictionary<string, List<Dictionary<string, object>>> ActionJsonParameter = null;
                                if (!String.IsNullOrEmpty(m[0].JsonParameter))
                                    ActionJsonParameter = new JavaScriptSerializer().Deserialize<Dictionary<string, List<Dictionary<string, object>>>>(m[0].JsonParameter);
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                    JsonParameter = new JavaScriptSerializer().Deserialize<Dictionary<string, List<Dictionary<string, object>>>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                ReturnData.Add(dataBusiness.FillData(viewSetting.Operations[m[0].OperationKey], m[0].Parameters, GetDataFormat(ActionJsonParameter, JsonParameter), GetOperationColums(viewSetting, userPermissions, ActionJsonParameter, JsonParameter), GetStartRecord(ActionJsonParameter, JsonParameter), GetMaxRecord(ActionJsonParameter, JsonParameter)));
                                break;
                            case OperationType.ExecuteNonQuery:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                ReturnData.Add(dataBusiness.ExecuteNonQuery(viewSetting.Operations[m[0].OperationKey], m[0].Parameters));
                                break;
                            case OperationType.ExecuteScalar:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }   
                                string ReturnType = "";  
                                if (!String.IsNullOrEmpty(m[0].JsonParameter))
                                    ReturnType = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(m[0].JsonParameter)["返回类型"];
                                else if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                    ReturnType = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter)["返回类型"];
                                switch (ReturnType)
                                {
                                    case "新增对象链接":
                                        string AutoID = dataBusiness.ExecuteScalar(viewSetting.Operations[m[0].OperationKey], m[0].Parameters).ToString();
                                        ReturnData.Add(AsynchronousLogin.GetAsynchronousLoginUrl(HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("&AsynchronousLoginKey=")).Replace("ViewProcess/Action/", "ViewProcess/Show/").Replace("/-1", "/" + AutoID), HttpContext.Current.Request.QueryString["Permissions"]) + HttpContext.Current.Request.Url.AbsoluteUri.Substring(HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("&", HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("AsynchronousLoginKey="))));
                                        break;
                                    default:
                                        ReturnData.Add(dataBusiness.ExecuteScalar(viewSetting.Operations[m[0].OperationKey], m[0].Parameters));
                                        break;
                                }
                                break;
                            case OperationType.ExecuteScalarNull:
                                if (dataBusiness == null) { dataBusiness = new DataBusiness(viewSetting.UserID, KeyList); }
                                var obj = dataBusiness.ExecuteScalar(viewSetting.Operations[m[0].OperationKey], m[0].Parameters);
                                if (obj != null)
                                {
                                    string Messing = "对象重复！";        
                                    if (!String.IsNullOrEmpty(m[0].JsonParameter))
                                        Messing = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(m[0].JsonParameter)["非空返回信息"];
                                    else if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                        Messing = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter)["非空返回信息"];
                                    if (m[0].Parameters != null)
                                        foreach (string n in m[0].Parameters.Keys)
                                            Messing = Messing.Replace(n, m[0].Parameters[n].ToString());     
                                    Messing = Messing.Replace("#ReturnObj", obj.ToString());
                                    throw new Exception(Messing);
                                }
                                ReturnData.Add(null);
                                break;
                            case OperationType.RemoveCache:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    List<string> cacheName = new JavaScriptSerializer().Deserialize<List<string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    foreach (string n in cacheName)
                                        CacheData.RemoveCache(n);
                                    ReturnData.Add(cacheName.Count);
                                }
                                else
                                {
                                    ReturnData.Add(0);
                                }
                                break;
                            case OperationType.ImageList:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "Images");
                                    if (Directory.Exists(FilePath))
                                    {
                                        string[] FileNames = Directory.GetFiles(FilePath);
                                        for (int i = 0; i < FileNames.Length; i++)
                                            FileNames[i] = Path.GetFileName(FileNames[i]);
                                        ReturnData.Add(FileNames);
                                    }
                                    else
                                        ReturnData.Add(null);
                                }
                                else
                                    ReturnData.Add(null);
                                break;
                            case OperationType.FileList:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "InternalFiles");
                                    if (Directory.Exists(FilePath))
                                    {
                                        string[] FileNames = Directory.GetFiles(FilePath);
                                        for (int i = 0; i < FileNames.Length; i++)
                                            FileNames[i] = Path.GetFileName(FileNames[i]);
                                        ReturnData.Add(FileNames);
                                    }
                                    else
                                        ReturnData.Add(null);
                                }
                                else
                                    ReturnData.Add(null);
                                break;
                            case OperationType.RenameFile:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "InternalFiles");
                                    if (Directory.Exists(FilePath))
                                    {
                                        Dictionary<string, object> NameObj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(m[0].JsonParameter);
                                        string FileName = NameObj["内部标识"].ToString();
                                        if ((bool)NameObj["外部下载"])
                                            FileName = FileName.Substring(0, FileName.IndexOf("_") + 16) + "^OL" + FileName.Substring(FileName.IndexOf("_") + 16);
                                        else
                                            FileName = FileName.Replace("^OL-", "-");
                                        FileName = FileName.Substring(0, FileName.IndexOf("-") + 1) + NameObj["文件名称"].ToString() + FileName.Substring(FileName.LastIndexOf("."));
                                        File.Move(FilePath + "\\" + NameObj["内部标识"].ToString(), FilePath + "\\" + FileName);
                                        ReturnData.Add(true);
                                    }
                                    else
                                        ReturnData.Add(false);
                                }
                                break;
                            case OperationType.DeleteFile:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "InternalFiles");
                                    if (Directory.Exists(FilePath))
                                    {
                                        Dictionary<string, string> NameObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(m[0].JsonParameter);
                                        File.Delete(FilePath + "\\" + NameObj["内部标识"].ToString());
                                        ReturnData.Add(true);
                                    }
                                    else
                                        ReturnData.Add(false);
                                }
                                break;
                            case OperationType.DeleteImage:
                                if (!String.IsNullOrEmpty(viewSetting.Operations[m[0].OperationKey].JsonParameter))
                                {
                                    Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[m[0].OperationKey].JsonParameter);
                                    string FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "Images");
                                    if (Directory.Exists(FilePath))
                                    {
                                        Dictionary<string, string> NameObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(m[0].JsonParameter);
                                        File.Delete(FilePath + "\\" + NameObj["内部标识"].ToString());
                                        string NameWithoutExtension = Path.GetFileNameWithoutExtension(FilePath + "\\" + NameObj["内部标识"].ToString());
                                        foreach (string n in Directory.GetFiles(FilePath))
                                        {
                                            if (n.IndexOf(NameWithoutExtension) > -1)
                                            {
                                                File.Delete(n);
                                            }
                                        }
                                        ReturnData.Add(true);
                                    }
                                    else
                                        ReturnData.Add(false);
                                }
                                break;
                        }

                return ReturnData;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string ActionUploadify(ViewSetting viewSetting, RouteValueDictionary KeyList, List<string> userPermissions, List<List<ActionOperation>> ActionParameters, HttpPostedFileBase FileData)
        {
            try
            {
                Dictionary<string, string> PathObj;
                string Extension;
                string FilePath;
                string FileName;

                foreach (List<ActionOperation> m in ActionParameters)
                    foreach (ActionOperation n in m)
                        if (!viewSetting.Operations.ContainsKey(n.OperationKey))
                            throw new Exception("没有找到操作：" + n.OperationKey + "。");
                        else if (!PermissionCheck.HasPermission(userPermissions, viewSetting.Operations[n.OperationKey].Permission))
                            throw new Exception("没有权限：" + viewSetting.Operations[n.OperationKey].Permission + "，无法进行操作：" + n.OperationKey + "。");

                switch (viewSetting.Operations[ActionParameters[0][0].OperationKey].OperationType)
                {
                    case OperationType.UpFile:
                        PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[ActionParameters[0][0].OperationKey].JsonParameter);
                        Extension = Path.GetExtension(FileData.FileName).ToLower();
                        if (PathObj["文件后序"].IndexOf(Extension) > -1)
                        {
                            FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "InternalFiles");
                            FileName = Path.GetFileName(FileData.FileName);
                            if (FileName.Length > 100)
                                FileName = FileName.Substring(0, 100) + Extension;
                            FileName = GetKey(KeyList, PathObj["文件前序"]) + "^" + GetKey(KeyList, PathObj["文件标识"]) + "_" + DateTime.Now.ToString("yyMMddHHmmssfff") + "-" + FileName;
                            if (!Directory.Exists(FilePath))
                                Directory.CreateDirectory(FilePath);
                            FileData.SaveAs(FilePath + "\\" + FileName);

                            return FileName;
                        }
                        else
                        {
                            throw new Exception("上传类别错误！");
                        }
                    case OperationType.UpImage:
                        PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[ActionParameters[0][0].OperationKey].JsonParameter);
                        Extension = Path.GetExtension(FileData.FileName).ToLower();
                        if (PathObj["文件后序"].IndexOf(Extension) > -1)
                        {
                            FilePath = GetPath(KeyList, PathObj["基目录"], PathObj["子目录"], "Images");
                            FileName = GetKey(KeyList, PathObj["文件前序"]) + "^" + GetKey(KeyList, PathObj["文件标识"]) + "_" + DateTime.Now.ToString("yyMMddHHmmssfff");
                            if (!Directory.Exists(FilePath))
                                Directory.CreateDirectory(FilePath);
                            FileData.SaveAs(FilePath + "\\" + FileName + Extension);
                            if (PathObj.ContainsKey("自动生成"))
                            {
                                string[] Ps;
                                string[] AutoMake = PathObj["自动生成"].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                                bool Expand = true;
                                foreach (string m in AutoMake)
                                {
                                    Ps = m.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                    if (Ps.Length == 4)
                                    {
                                        if (Ps[0] == "Expand")
                                            Expand = false;
                                        Tools.Image.MakeThumbnail(FilePath + "\\" + FileName + Extension, FilePath + "\\" + FileName + "-" + Ps[0], int.Parse(Ps[1]), int.Parse(Ps[2]), Ps[3]);
                                    }
                                }
                                if (Expand)
                                    Tools.Image.MakeThumbnail(FilePath + "\\" + FileName + Extension, FilePath + "\\" + FileName + "-Expand", 240, 180, "Expand");
                            }
                            return FileName;
                        }
                        else
                        {
                            throw new Exception("上传类别错误！");
                        }
                    default:
                        return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
